package com.uduemc.biso.node.web.api.design.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.uduemc.biso.node.core.common.entities.SiteConfig;
import com.uduemc.biso.node.core.common.utils.AssetsUtil;
import com.uduemc.biso.node.core.entities.custom.CustomThemeColor;
import com.uduemc.biso.node.core.property.GlobalProperties;
import com.uduemc.biso.node.core.utils.SitePathUtil;
import com.uduemc.biso.node.web.api.component.SiteHolder;
import com.uduemc.biso.node.web.api.exception.NotFoundException;
import com.uduemc.biso.node.web.api.service.SConfigService;

import cn.hutool.core.util.StrUtil;

@Controller
@RequestMapping("/api/design")
public class DAssetsController {

	private static final Logger logger = LoggerFactory.getLogger(DAssetsController.class);

	@Autowired
	private SiteHolder siteHolder;

	@Autowired
	private GlobalProperties globalProperties;

	@Autowired
	private SConfigService sConfigServiceImpl;

	/**
	 * 当前网站的 favicon.ico 的图标
	 * 
	 * @param response
	 * @throws NotFoundException
	 */
	@GetMapping(value = { "/*/*/favicon.ico" })
	@ResponseBody
	public void favicon(HttpServletResponse response) throws NotFoundException {
		// 获取 ico 文件路径
		String userPathByCode = SitePathUtil.getUserPathByCode(globalProperties.getSite().getBasePath(), siteHolder.getHost().getRandomCode());
		String imagePath = userPathByCode + "/favicon.ico";

		if (!(new File(imagePath).isFile())) {
			return;
		}

		FileInputStream openInputStream = null;
		File file = null;
		try {
			file = new File(imagePath);
			openInputStream = FileUtils.openInputStream(file);

			if (openInputStream == null) {
				throw new RuntimeException("读取 ico 图片文件失败！ imagePath: " + imagePath);
			}

			long size = file.length();
			response.setHeader("Accept-Ranges", "bytes");
			response.setHeader("Content-Length", "" + size);
			byte[] temp = new byte[(int) size];
			openInputStream.read(temp, 0, (int) size);
			openInputStream.close();
			byte[] data = temp;
			OutputStream out = response.getOutputStream();
			response.setContentType("image/x-icon");
			out.write(data);

			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (openInputStream != null) {
				try {
					openInputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		return;
	}

	@GetMapping(value = { "/*/*/assets/static/site/np_template/{themenum}/css/color_custom.css" })
	@ResponseBody
	public void colorCustom(@PathVariable("themenum") String themenum, HttpServletResponse response)
			throws NotFoundException, JsonParseException, JsonMappingException, IOException {
		if (siteHolder == null) {
			response.setStatus(404);
			return;
		}
		SiteConfig siteConfig = siteHolder.getSiteConfig();
		if (siteConfig == null) {
			response.setStatus(404);
			return;
		}
		String theme = siteConfig.getSConfig().getTheme();
		String customThemeColorConfig = siteConfig.getSConfig().getCustomThemeColorConfig();
		if (StrUtil.isBlank(theme) || StrUtil.isBlank(customThemeColorConfig)) {
			response.setStatus(404);
			return;
		}

		if (!theme.equals(themenum)) {
			response.setStatus(404);
			return;
		}

		CustomThemeColor customThemeColor = sConfigServiceImpl.getCustomThemeColor(siteConfig.getSConfig());
		if (customThemeColor == null || StrUtil.isBlank(customThemeColor.getCss())) {
			response.setStatus(404);
			return;
		}

		String content = AssetsUtil.customThemeColorContext(globalProperties.getSite().getAssetsPath(), theme, customThemeColor);
		if (StrUtil.isBlank(content)) {
			content = "";
			return;
		}
		response.setContentType("text/css; charset=utf-8");
		response.getWriter().write(content);
		return;
	}

	@GetMapping(value = { "/*/*/assets/**" })
	@ResponseBody
	public void index(HttpServletResponse response) throws NotFoundException {
		if (!validThemeNum()) {
			throw new NotFoundException("当前的站点主题无法匹配模板的编号");
		}

		// 资源链接
		String siteUri = siteHolder.getSiteBasic().getSiteUri();
		// 获取后缀
		String suffix = StringUtils.unqualify(siteUri);
		if (suffix.equals("css")) {
			cssResponse(response);
		} else if (suffix.equals("js")) {
			jsResponse(response);
		} else if (suffix.equals("png") || suffix.equals("jpg") || suffix.equals("gif")) {
			imageResponse(response, suffix);
		} else if (suffix.equals("eot") || suffix.equals("svg") || suffix.equals("ttf") || suffix.equals("woff") || suffix.equals("woff2")) {
			fontResponse(response);
		} else {
			logger.error("未识别的后缀！suffix: " + suffix);
			throw new NotFoundException("未识别的后缀！suffix: " + suffix);
		}

		return;
	}

	protected void fontResponse(HttpServletResponse response) throws NotFoundException {
		response.setContentType("application/octet-stream");
		FileInputStream openInputStream = null;
		File file = null;
		String imagePath = AssetsUtil.getAssetsPathImage(globalProperties.getSite().getAssetsPath(), siteHolder.getSiteBasic().getSiteUri());
		try {
			file = new File(imagePath);
			openInputStream = FileUtils.openInputStream(file);

			if (openInputStream == null) {
				throw new NotFoundException("读取 assets 文件失败！ siteUri: " + siteHolder.getSiteBasic().getSiteUri());
			}
			long size = file.length();
			response.setHeader("Accept-Ranges", "bytes");
			response.setHeader("Content-Length", "" + size);
			byte[] temp = new byte[(int) size];
			openInputStream.read(temp, 0, (int) size);
			openInputStream.close();
			byte[] data = temp;
			OutputStream out = response.getOutputStream();
			out.write(data);

			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
			throw new NotFoundException("读取 assets 文件失败！ siteUri: " + siteHolder.getSiteBasic().getSiteUri());
		} finally {
			if (openInputStream != null) {
				try {
					openInputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	protected void imageResponse(HttpServletResponse response, String suffix) throws NotFoundException {
		FileInputStream openInputStream = null;
		File file = null;
		String imagePath = AssetsUtil.getAssetsPathImage(globalProperties.getSite().getAssetsPath(), siteHolder.getSiteBasic().getSiteUri());
		try {
			file = new File(imagePath);
			openInputStream = FileUtils.openInputStream(file);

			if (openInputStream == null) {
				throw new NotFoundException("读取 assets 文件失败！ siteUri: " + siteHolder.getSiteBasic().getSiteUri());
			}

			long size = file.length();
			response.setHeader("Accept-Ranges", "bytes");
			response.setHeader("Content-Length", "" + size);
			byte[] temp = new byte[(int) size];
			openInputStream.read(temp, 0, (int) size);
			openInputStream.close();
			byte[] data = temp;
			OutputStream out = response.getOutputStream();
			response.setContentType("image/" + suffix);
			out.write(data);

			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
			throw new NotFoundException("读取 assets 文件失败！ siteUri: " + siteHolder.getSiteBasic().getSiteUri());
		} finally {
			if (openInputStream != null) {
				try {
					openInputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	protected void jsResponse(HttpServletResponse response) throws NotFoundException {
		// application/javascript; charset=utf-8
		response.setContentType("application/javascript; charset=utf-8");
		String content = "";
		try {
			content = AssetsUtil.getAssetsFileCss(globalProperties.getSite().getAssetsPath(), siteHolder.getSiteBasic().getSiteUri());
			response.getWriter().write(content);
		} catch (IOException e) {
			e.printStackTrace();
			throw new NotFoundException("读取 assets 文件失败！ siteUri: " + siteHolder.getSiteBasic().getSiteUri());
		}
	}

	protected void cssResponse(HttpServletResponse response) throws NotFoundException {
		// content-type: text/css; charset=utf-8
		response.setContentType("text/css; charset=utf-8");
		String content = "";
		try {
			content = AssetsUtil.getAssetsFileCss(globalProperties.getSite().getAssetsPath(), siteHolder.getSiteBasic().getSiteUri());
			response.getWriter().write(content);
		} catch (IOException e) {
			e.printStackTrace();
			throw new NotFoundException("读取 assets 文件失败！ siteUri: " + siteHolder.getSiteBasic().getSiteUri());
		}
	}

	// 验证当前请求的是否是模板内的样式，如果是则判断与当前的模板编号是否相符
	protected boolean validThemeNum() {
		Pattern compile = Pattern.compile("^/assets/template/(\\d+)/");
		Matcher matcher = compile.matcher(siteHolder.getSiteBasic().getSiteUri());
		if (matcher.find()) {
			String group = matcher.group(1);
			if (StringUtils.isEmpty(group)) {
				return false;
			}
			if (siteHolder.getSiteConfig().getSConfig().getTheme() == null || !group.equals(siteHolder.getSiteConfig().getSConfig().getTheme())) {
				return false;
			}
		}
		return true;
	}
}
